<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="工种名称">
        <el-input v-model="queryParams.name" placeholder="请输入工种名称" clearable @keyup.enter="getList" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="Plus" @click="open=true">新增</el-button>
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" v-if="refreshTable" :data="tableData" row-key="id" :default-expand-all="isExpandAll" :tree-props="{ children: 'children'}">
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="gmtCreate" />
      <el-table-column label="操作" align="center" width="250">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog title="新增/编辑工种" v-model="open" width="600px" append-to-body :before-close="handleClose">
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工种名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入工种名称" />
        </el-form-item>
        <el-form-item label="层级">
          <el-input :value="form.level+1" placeholder="请输入层级" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="editLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();

const deptList = ref([]);
let depTree = ref([]);
const open = ref(false);
let loading = ref(false);
let editLoading = ref(false);
const isExpandAll = ref(true);
const refreshTable = ref(true);

let tableData = ref([]);

let queryParams = ref({
  name: "",
  pid: "",
  level: null,
});
let form = ref({
  pid: 0,
  name: null,
  level: 0,
});
let rules = ref({
  name: [{ required: true, message: "工种名称不能为空", trigger: "blur" }],
});

onMounted(() => {
  getList();
});

/** 查询部门列表 */
async function getList() {
  try {
    loading.value = true;
    let resp = await proxy.$apis.workTypeList(queryParams.value);
    if (queryParams.value.name) {
      tableData.value = resp;
    } else {
      tableData.value = proxy.$utils.transformArray(resp, "id", "pid");
    }
    //tableData.value = resp;
    console.log("tableData.value", tableData.value);
  } catch (error) {
  } finally {
    loading.value = false;
  }
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    name: "",
    pid: "",
    level: null,
  };
  getList();
}
/** 新增按钮操作 */
function handleAdd(row) {
  form.value.pid = row.id;
  let level = findLevel(tableData.value, row.id);
  form.value.level = level + 1;
  open.value = true;
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  form.value = proxy.$utils.formatFunction(row, { ...form.value });
  form.value.id = row.id;
  form.value.level = findLevel(tableData.value, row.id);
  open.value = true;
}
// 判断某个子项所在的层级
function findLevel(arr, targetId, level = 0) {
  for (let item of arr) {
    if (item.id == targetId) {
      return level;
    }
    if (item.children) {
      let result = findLevel(item.children, targetId, level + 1);
      if (result) return result;
    }
  }
  return null;
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate((valid) => {
    if (valid) save();
  });
}
let handleClose = () => {
  form.value = {
    pid: 0,
    name: null,
    level: 0,
  };
  proxy.$refs.deptRef.resetFields();
  getList();
  open.value = false;
};
let save = async () => {
  try {
    editLoading.value = true;
    if (form.value.id) {
      await proxy.$apis.workTypeUpdate(form.value);
    } else {
      await proxy.$apis.workTypeAdd(form.value);
    }
    proxy.$utils.showToast("操作成功");
    handleClose();
  } catch (error) {
  } finally {
    editLoading.value = false;
  }
};
/** 删除按钮操作 */
async function handleDelete(row) {
  let resp = await proxy.$utils.confirmTips(
    '是否确认删除名称为"' + row.name + '"的数据项?'
  );
  if (!resp) return;
  await proxy.$apis.workTypeDel({
    ids: [row.id],
  });
  getList();
  proxy.$modal.msgSuccess("删除成功");
}
</script>
